package com.practice.springboot_01_zwj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.practice.springboot_01_zwj.controller.CloudNetworkController;
import com.practice.springboot_01_zwj.entity.*;
import com.practice.springboot_01_zwj.mapper.CloudNetworkMapper;
import com.practice.springboot_01_zwj.service.CloudNetworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class CloudNetworkServiceImpl implements CloudNetworkService {
    @Autowired
    private CloudNetworkMapper dao;

    @Override
    public PageInfo<CloudNetwork> selectByCityCode(String cityCode, String providerType, int pageNum, int pageSize) {
        // 1. 参数校验
        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        // 2. 确保在查询前启动分页（这是关键步骤）
        PageHelper.startPage(pageNum, pageSize);

        // 3. 处理空字符串情况
        if (providerType != null && providerType.isEmpty()) {
            providerType = null;
        }

        // 4. 执行查询（必须在 startPage 之后立即调用）
        List<CloudNetwork> networks = dao.selectByCityCode(cityCode, providerType);

        // 5. 使用 PageInfo 包装结果
        return new PageInfo<>(networks);
    }

    @Override
    public int addNetworkCustomer(CloudNetwork cloudNetwork) {
        return dao.addNetworkCustomer(cloudNetwork);
    }

    @Override
    public int updateNetworkCustomer(CloudNetwork cloudNetwork) {
        return dao.updateNetworkCustomer(cloudNetwork);
    }

    @Override
    public int deleteNetworkCustomer(Integer id) {
        return dao.deleteNetworkCustomer(id);
    }
    @Override
    public PageInfo<CloudNetwork> selectByCityCodeAndCustomerType(
            String cityCode,
            String customerType,String  districtName,String customerName,
            int pageNum,
            int pageSize
    ) {
        // 1. 参数校验
        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 20;

        // 2. 启动分页
        PageHelper.startPage(pageNum, pageSize);

        // 3. 处理空字符串和null值
        if (cityCode != null && cityCode.isEmpty()) {
            cityCode = null;
        }
        if (customerType != null && customerType.isEmpty()) {
            customerType = null;
        }

        // 4. 执行查询
        List<CloudNetwork> networks = dao.selectByCityCodeAndCustomerType(cityCode, customerType,districtName,customerName);

        // 5. 返回分页结果
        return new PageInfo<>(networks);
    }

    @Override
    public List<CloudNetworkController.CityStatsDTO> getCityStats() {
        try {
            // 获取所有统计数据
            List<Map<String, Object>> cityCounts = dao.countByCityCode();
            List<Map<String, Object>> cityCustomerTypeCounts = dao.countByCityCodeAndCustomerType();
            List<Map<String, Object>> districtCounts = dao.countByCityCodeAndDistrict();
            List<Map<String, Object>> districtCustomerTypeCounts = dao.countByCityCodeAndDistrictAndCustomerType();

            // 获取所有可能的客户类型
            Set<String> allCustomerTypes = getAllCustomerTypes(cityCustomerTypeCounts, districtCustomerTypeCounts);

            // 创建结果列表
            List<CloudNetworkController.CityStatsDTO> result = new ArrayList<>();

            // 按城市代码分组客户类型统计数据
            Map<String, List<CloudNetworkController.CustomerTypeStats>> cityCustomerTypeMap = groupCityCustomerTypeStats(cityCustomerTypeCounts);

            // 按城市代码和区县分组客户类型统计数据
            Map<String, Map<String, List<CloudNetworkController.CustomerTypeStats>>> districtCustomerTypeMap = groupDistrictCustomerTypeStats(districtCustomerTypeCounts);

            // 按城市代码分组区县统计数据
            Map<String, List<CloudNetworkController.DistrictStats>> districtMap = groupDistrictStats(districtCounts, districtCustomerTypeMap);

            // 构建最终结果
            buildFinalResult(cityCounts, cityCustomerTypeMap, districtMap, allCustomerTypes, result);

            return result;
        } catch (Exception e) {
            throw new RuntimeException("获取地市统计信息失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<CloudNetwork> selectDistrictName(String cityCode) {
        return dao.selectDistrictName(cityCode);
    }


    // 获取所有可能的客户类型
    private Set<String> getAllCustomerTypes(
            List<Map<String, Object>> cityCustomerTypeCounts,
            List<Map<String, Object>> districtCustomerTypeCounts) {
        Set<String> allCustomerTypes = new HashSet<>();

        // 从城市客户类型统计数据中获取所有客户类型
        for (Map<String, Object> item : cityCustomerTypeCounts) {
            String customerType = (String) item.get("customerType");
            if (customerType != null) {
                allCustomerTypes.add(customerType);
            }
        }

        // 从区县客户类型统计数据中获取所有客户类型
        for (Map<String, Object> item : districtCustomerTypeCounts) {
            String customerType = (String) item.get("customerType");
            if (customerType != null) {
                allCustomerTypes.add(customerType);
            }
        }

        return allCustomerTypes;
    }

    // 按城市代码分组客户类型统计数据
    private Map<String, List<CloudNetworkController.CustomerTypeStats>> groupCityCustomerTypeStats(
            List<Map<String, Object>> cityCustomerTypeCounts) {
        Map<String, List<CloudNetworkController.CustomerTypeStats>> cityCustomerTypeMap = new HashMap<>();

        for (Map<String, Object> item : cityCustomerTypeCounts) {
            String cityCode = (String) item.get("cityCode");
            String customerType = (String) item.get("customerType");
            Integer count = ((Long) item.get("count")).intValue();

            CloudNetworkController.CustomerTypeStats stats = new CloudNetworkController.CustomerTypeStats();
            stats.setCustomerType(customerType);
            stats.setCount(count);

            cityCustomerTypeMap.computeIfAbsent(cityCode, k -> new ArrayList<>()).add(stats);
        }

        return cityCustomerTypeMap;
    }

    // 按城市代码和区县分组客户类型统计数据
    private Map<String, Map<String, List<CloudNetworkController.CustomerTypeStats>>> groupDistrictCustomerTypeStats(
            List<Map<String, Object>> districtCustomerTypeCounts) {
        Map<String, Map<String, List<CloudNetworkController.CustomerTypeStats>>> districtCustomerTypeMap = new HashMap<>();

        for (Map<String, Object> item : districtCustomerTypeCounts) {
            String cityCode = (String) item.get("cityCode");
            String districtName = (String) item.get("districtName");
            String customerType = (String) item.get("customerType");
            Integer count = ((Long) item.get("count")).intValue();

            CloudNetworkController.CustomerTypeStats stats = new CloudNetworkController.CustomerTypeStats();
            stats.setCustomerType(customerType);
            stats.setCount(count);

            districtCustomerTypeMap
                    .computeIfAbsent(cityCode, k -> new HashMap<>())
                    .computeIfAbsent(districtName, k -> new ArrayList<>())
                    .add(stats);
        }

        return districtCustomerTypeMap;
    }

    // 按城市代码分组区县统计数据
    private Map<String, List<CloudNetworkController.DistrictStats>> groupDistrictStats(
            List<Map<String, Object>> districtCounts,
            Map<String, Map<String, List<CloudNetworkController.CustomerTypeStats>>> districtCustomerTypeMap) {
        Map<String, List<CloudNetworkController.DistrictStats>> districtMap = new HashMap<>();

        for (Map<String, Object> item : districtCounts) {
            String cityCode = (String) item.get("cityCode");
            String districtName = (String) item.get("districtName");
            Integer totalCount = ((Long) item.get("totalCount")).intValue();

            CloudNetworkController.DistrictStats stats = new CloudNetworkController.DistrictStats();
            stats.setDistrictName(districtName);
            stats.setTotalCount(totalCount);

            // 添加客户类型统计数据
            if (districtCustomerTypeMap.containsKey(cityCode) &&
                    districtCustomerTypeMap.get(cityCode).containsKey(districtName)) {
                stats.setCustomerTypeStats(districtCustomerTypeMap.get(cityCode).get(districtName));
            } else {
                stats.setCustomerTypeStats(new ArrayList<>());
            }

            districtMap.computeIfAbsent(cityCode, k -> new ArrayList<>()).add(stats);
        }

        return districtMap;
    }

    // 构建最终结果
    private void buildFinalResult(
            List<Map<String, Object>> cityCounts,
            Map<String, List<CloudNetworkController.CustomerTypeStats>> cityCustomerTypeMap,
            Map<String, List<CloudNetworkController.DistrictStats>> districtMap,
            Set<String> allCustomerTypes,
            List<CloudNetworkController.CityStatsDTO> result) {

        for (Map<String, Object> cityCount : cityCounts) {
            String cityCode = (String) cityCount.get("cityCode");
            Integer totalCount = ((Long) cityCount.get("totalCount")).intValue();

            CloudNetworkController.CityStatsDTO cityStats = new CloudNetworkController.CityStatsDTO();
            cityStats.setCityCode(cityCode);
            cityStats.setTotalCount(totalCount);

            // 添加客户类型统计数据
            List<CloudNetworkController.CustomerTypeStats> customerTypeStatsList = new ArrayList<>();
            if (cityCustomerTypeMap.containsKey(cityCode)) {
                customerTypeStatsList.addAll(cityCustomerTypeMap.get(cityCode));
            }

            // 补全缺失的客户类型，计数为0
            for (String customerType : allCustomerTypes) {
                boolean exists = false;
                for (CloudNetworkController.CustomerTypeStats stats : customerTypeStatsList) {
                    if (customerType.equals(stats.getCustomerType())) {
                        exists = true;
                        break;
                    }
                }

                if (!exists) {
                    CloudNetworkController.CustomerTypeStats stats = new CloudNetworkController.CustomerTypeStats();
                    stats.setCustomerType(customerType);
                    stats.setCount(0);
                    customerTypeStatsList.add(stats);
                }
            }

            cityStats.setCustomerTypeStats(customerTypeStatsList);

            // 添加区县统计数据
            List<CloudNetworkController.DistrictStats> districtStatsList = new ArrayList<>();
            if (districtMap.containsKey(cityCode)) {
                for (CloudNetworkController.DistrictStats districtStat : districtMap.get(cityCode)) {
                    // 补全区县中缺失的客户类型，计数为0
                    List<CloudNetworkController.CustomerTypeStats> districtCustomerTypeStatsList = new ArrayList<>();
                    if (districtStat.getCustomerTypeStats() != null) {
                        districtCustomerTypeStatsList.addAll(districtStat.getCustomerTypeStats());
                    }

                    for (String customerType : allCustomerTypes) {
                        boolean exists = false;
                        for (CloudNetworkController.CustomerTypeStats stats : districtCustomerTypeStatsList) {
                            if (customerType.equals(stats.getCustomerType())) {
                                exists = true;
                                break;
                            }
                        }

                        if (!exists) {
                            CloudNetworkController.CustomerTypeStats stats = new CloudNetworkController.CustomerTypeStats();
                            stats.setCustomerType(customerType);
                            stats.setCount(0);
                            districtCustomerTypeStatsList.add(stats);
                        }
                    }

                    CloudNetworkController.DistrictStats enhancedDistrictStat = new CloudNetworkController.DistrictStats();
                    enhancedDistrictStat.setDistrictName(districtStat.getDistrictName());
                    enhancedDistrictStat.setTotalCount(districtStat.getTotalCount());
                    enhancedDistrictStat.setCustomerTypeStats(districtCustomerTypeStatsList);

                    districtStatsList.add(enhancedDistrictStat);
                }
            }

            cityStats.setDistrictStats(districtStatsList);

            result.add(cityStats);
        }
    }

//政务外网商机清单增删改查
    @Override
    public int addNetworkShangJi(CloudNetwork cloudNetwork) {
        return dao.addNetworkShangJi(cloudNetwork);
    }

    @Override
    public int updateNetworkShangJi(CloudNetwork cloudNetwork) {
        return dao.updateNetworkShangJi(cloudNetwork);
    }

    @Override
    public int deleteNetworkShangJi(Integer id) {
        return dao.deleteNetworkShangJi(id);
    }
    @Override
    public PageInfo<CloudNetwork> selectByCityCodeAndProviderType(
            String cityCode,
            String providerType,
            String districtName,
            int pageNum,
            int pageSize) {

        // 调用重载方法，默认不筛选合同结束时间
        return selectByCityCodeAndProviderType(cityCode, providerType, districtName, false, pageNum, pageSize);
    }

    @Override
    public PageInfo<CloudNetwork> selectByCityCodeAndProviderType(
            String cityCode,
            String providerType,
            String districtName,
            Boolean filterByContractEndTime,
            int pageNum,
            int pageSize) {

        // 1. 参数校验
        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        // 处理空字符串情况
        if (cityCode != null && cityCode.isEmpty()) {
            cityCode = null;
        }
        if (providerType != null && providerType.isEmpty()) {
            providerType = null;
        }
        if (districtName != null && districtName.isEmpty()) {
            districtName = null;
        }

        // 处理filterByContractEndTime参数
        if (filterByContractEndTime == null) {
            filterByContractEndTime = false;
        }

        // 2. 执行查询 - 先获取所有数据
        List<CloudNetwork> allNetworks = dao.selectByCityCodeAndProviderType(
                cityCode, providerType, districtName, false // 这里不筛选合同结束时间
        );

        // 3. 额外验证日期格式并过滤无效数据（如果启用了筛选）
        if (filterByContractEndTime) {
            allNetworks = filterValidContractEndTime(allNetworks);
        }

        // 4. 手动分页处理
        int total = allNetworks.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        if (fromIndex > total) {
            fromIndex = total;
        }

        List<CloudNetwork> pageList = allNetworks.subList(fromIndex, toIndex);

        // 5. 创建PageInfo对象
        PageInfo<CloudNetwork> pageInfo = new PageInfo<>(pageList);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        pageInfo.setPages((int) Math.ceil((double) total / pageSize));

        // 设置是否有上一页/下一页
        pageInfo.setHasPreviousPage(pageNum > 1);
        pageInfo.setHasNextPage(pageNum < pageInfo.getPages());
        pageInfo.setIsFirstPage(pageNum == 1);
        pageInfo.setIsLastPage(pageNum == pageInfo.getPages());

        return pageInfo;
    }

    /**
     * 过滤有效的合同结束时间
     * @param networks 原始网络数据列表
     * @return 过滤后的网络数据列表
     */
    private List<CloudNetwork> filterValidContractEndTime(List<CloudNetwork> networks) {
        List<CloudNetwork> validNetworks = new ArrayList<>();

        // 获取当前年份的1月1号和12月31号
        LocalDate now = LocalDate.now();
        LocalDate yearStart = LocalDate.of(now.getYear(), 1, 1);
        LocalDate yearEnd = LocalDate.of(now.getYear(), 12, 31);

        for (CloudNetwork network : networks) {
            if (network.getContractEndTime() != null && !network.getContractEndTime().isEmpty()) {
                try {
                    // 尝试解析日期
                    LocalDate endDate = LocalDate.parse(network.getContractEndTime());

                    // 验证日期是否在当前年1月1号和年底之间
                    if (!endDate.isBefore(yearStart) && !endDate.isAfter(yearEnd)) {
                        validNetworks.add(network);
                    }
                } catch (DateTimeParseException e) {
                    // 日期格式无效，跳过此项
                }
            }
        }

        return validNetworks;
    }

    @Override
    public List<Map<String, Object>> countShangJiByCityCode() {
        return dao.countShangJiByCityCode();
    }

    @Override
    public List<Map<String, Object>> countByFourLevelClassify(Boolean filterByContractEndTime,String providerType) {
        // 获取数据库中的统计数据
        List<Map<String, Object>> dbResult = dao.countByFourLevelClassify(filterByContractEndTime,providerType);

        // 定义所有可能的分类
        String[] allClassifies = {"省本级","村屯社区级","乡镇街道级", "区县级", "市本级", "未知"};

        // 创建一个映射，按城市组织数据
        Map<String, Map<String, Integer>> cityDataMap = new HashMap<>();

        // 初始化所有城市的映射
        for (Map<String, Object> item : dbResult) {
            String cityCode = (String) item.get("cityCode");
            if (!cityDataMap.containsKey(cityCode)) {
                cityDataMap.put(cityCode, new HashMap<>());
                // 初始化所有分类为0
                for (String classify : allClassifies) {
                    cityDataMap.get(cityCode).put(classify, 0);
                }
            }

            String classify = (String) item.get("fourLevelClassify");
            Integer count = ((Long) item.get("count")).intValue();
            cityDataMap.get(cityCode).put(classify, count);
        }

        // 构建最终结果
        List<Map<String, Object>> finalResult = new ArrayList<>();
        for (String cityCode : cityDataMap.keySet()) {
            Map<String, Integer> classifyCounts = cityDataMap.get(cityCode);
            for (String classify : allClassifies) {
                Map<String, Object> item = new HashMap<>();
                item.put("cityCode", cityCode);
                item.put("fourLevelClassify", classify);
                item.put("count", classifyCounts.get(classify));
                finalResult.add(item);
            }
        }

        // 按城市代码排序
        finalResult.sort((a, b) -> {
            String cityA = (String) a.get("cityCode");
            String cityB = (String) b.get("cityCode");
            return cityA.compareTo(cityB);
        });

        return finalResult;
    }

//政务云客户清单增删改查
    @Override
    public int addCloudCustomerType(CloudNetwork cloudNetwork) {
        return dao.addCloudCustomerType(cloudNetwork);
    }

    @Override
    public int updateCloudCustomerType(CloudNetwork cloudNetwork) {
        return dao.updateCloudCustomerType(cloudNetwork);
    }

    @Override
    public int deleteCloudCustomerType(Integer id) {
        return dao.deleteCloudCustomerType(id);
    }

    @Override
    public PageInfo<CloudNetwork> selectCloudCustomerType(String cityCode,String customerType,String providerType, int pageNum, int pageSize) {
        // 1. 参数校验
        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        // 2. 确保在查询前启动分页（这是关键步骤）
        PageHelper.startPage(pageNum, pageSize);

        // 4. 执行查询（必须在 startPage 之后立即调用）
        List<CloudNetwork> networks = dao.selectCloudCustomerType(cityCode,customerType,providerType);

        // 5. 使用 PageInfo 包装结果
        return new PageInfo<>(networks);
    }

    @Override
    public List<Map<String, Object>> countByCustomerType() {
        // 获取数据库中的统计数据
        List<Map<String, Object>> dbResult = dao.countByCustomerType();

        // 定义所有客户类型
        List<String> allCustomerTypes = Arrays.asList(
                "党政", "交通", "教育", "医卫", "执法"
        );

        // 创建一个映射，存储每个城市的总公司数
        Map<String, Integer> cityTotalCompanyCount = new HashMap<>();

        // 创建一个映射，按城市组织数据
        Map<String, Map<String, Object>> cityDataMap = new HashMap<>();

        // 第一遍遍历：计算每个城市的总公司数
        for (Map<String, Object> item : dbResult) {
            String cityCode = (String) item.get("cityCode");
            Integer companyCount = ((Long) item.get("companyCount")).intValue();

            // 累加每个城市的总公司数
            cityTotalCompanyCount.put(cityCode,
                    cityTotalCompanyCount.getOrDefault(cityCode, 0) + companyCount);
        }

        // 第二遍遍历：初始化所有城市的映射
        for (String cityCode : cityTotalCompanyCount.keySet()) {
            Map<String, Object> cityData = new HashMap<>();
            cityData.put("cityCode", cityCode);
            cityData.put("totalCount", cityTotalCompanyCount.get(cityCode)); // 使用公司数作为总数

            // 初始化客户类型统计
            List<Map<String, Object>> customerTypeStats = new ArrayList<>();
            for (String customerType : allCustomerTypes) {
                Map<String, Object> typeStat = new HashMap<>();
                typeStat.put("customerType", customerType);
                typeStat.put("count", 0);
                customerTypeStats.add(typeStat);
            }
            cityData.put("customerTypeStats", customerTypeStats);

            cityDataMap.put(cityCode, cityData);
        }

        // 第三遍遍历：填充客户类型数据
        for (Map<String, Object> item : dbResult) {
            String cityCode = (String) item.get("cityCode");
            String customerType = (String) item.get("customerType");
            Integer companyCount = ((Long) item.get("companyCount")).intValue();

            // 更新特定客户类型的计数
            Map<String, Object> cityData = cityDataMap.get(cityCode);
            if (cityData != null) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> customerTypeStats = (List<Map<String, Object>>) cityData.get("customerTypeStats");
                for (Map<String, Object> typeStat : customerTypeStats) {
                    if (customerType.equals(typeStat.get("customerType"))) {
                        typeStat.put("count", companyCount);
                        break;
                    }
                }
            }
        }

        // 构建最终结果
        List<Map<String, Object>> finalResult = new ArrayList<>();
        for (String cityCode : cityDataMap.keySet()) {
            finalResult.add(cityDataMap.get(cityCode));
        }

        // 按城市代码排序
        finalResult.sort((a, b) -> {
            String cityA = (String) a.get("cityCode");
            String cityB = (String) b.get("cityCode");
            return cityA.compareTo(cityB);
        });

        return finalResult;
    }

//政务云商机清单的增删改查
    @Override
    public int addCloudComplete(CloudNetwork cloudNetwork) {
        return dao.addCloudComplete(cloudNetwork);
    }

    @Override
    public int updateCloudComplete(CloudNetwork cloudNetwork) {
        return dao.updateCloudComplete(cloudNetwork);
    }

    @Override
    public int deleteCloudComplete(Integer id) {
        return dao.deleteCloudComplete(id);
    }

    @Override
    public PageInfo<CloudNetwork> selectCloudComplete(
            String cityCode,
            String providerType,
            int pageNum,
            int pageSize) {

        // 调用重载方法，默认不筛选合同结束时间
        return selectCloudComplete(cityCode, providerType, false, pageNum, pageSize);
    }

    @Override
    public PageInfo<CloudNetwork> selectCloudComplete(
            String cityCode,
            String providerType,
            Boolean filterByContractEndTime,
            int pageNum,
            int pageSize) {

        // 1. 参数校验
        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        // 处理空字符串情况
        if (cityCode != null && cityCode.isEmpty()) {
            cityCode = null;
        }
        if (providerType != null && providerType.isEmpty()) {
            providerType = null;
        }

        // 处理filterByContractEndTime参数
        if (filterByContractEndTime == null) {
            filterByContractEndTime = false;
        }

        // 2. 执行查询 - 先获取所有数据
        List<CloudNetwork> allNetworks = dao.selectCloudComplete(
                cityCode, providerType, false // 这里不筛选合同结束时间
        );

        // 3. 额外验证日期格式并过滤无效数据（如果启用了筛选）
        if (filterByContractEndTime) {
            // 筛选合同结束时间在今年的数据
            List<CloudNetwork> filteredByTime = filterValidContractEndTime(allNetworks);

            // 获取所有providerType='未招标'的数据
            List<CloudNetwork> weizhaobiaoNetworks = allNetworks.stream()
                    .filter(network -> "未招标".equals(network.getProviderType()))
                    .collect(Collectors.toList());

            // 合并结果：合同结束时间在今年的数据 + 所有未招标的数据
            Set<CloudNetwork> mergedSet = new LinkedHashSet<>(filteredByTime);
            mergedSet.addAll(weizhaobiaoNetworks);
            allNetworks = new ArrayList<>(mergedSet);
        }

        // 4. 手动分页处理
        int total = allNetworks.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        if (fromIndex > total) {
            fromIndex = total;
        }

        List<CloudNetwork> pageList = allNetworks.subList(fromIndex, toIndex);

        // 5. 创建PageInfo对象
        PageInfo<CloudNetwork> pageInfo = new PageInfo<>(pageList);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        pageInfo.setPages((int) Math.ceil((double) total / pageSize));

        // 设置是否有上一页/下一页
        pageInfo.setHasPreviousPage(pageNum > 1);
        pageInfo.setHasNextPage(pageNum < pageInfo.getPages());
        pageInfo.setIsFirstPage(pageNum == 1);
        pageInfo.setIsLastPage(pageNum == pageInfo.getPages());

        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> countCloudCompleteByCityCode() {
        return dao.countCloudCompleteByCityCode();
    }

    @Override
    public List<Map<String, Object>> countCloudCompleteByContractEndTime(String cityCode, String providerType, Boolean filterByContractEndTime) {
        // 获取所有数据
        List<Map<String, Object>> allCounts = dao.countCloudCompleteByContractEndTime(cityCode, providerType, false);

        // 如果不需要按合同结束时间过滤，直接返回
        if (filterByContractEndTime == null || !filterByContractEndTime) {
            return allCounts;
        }

        // 如果需要过滤，获取所有详细数据并应用与内层查询相同的过滤逻辑
        List<CloudNetwork> allNetworks = dao.selectCloudComplete(cityCode, providerType, false);

        // 应用与内层查询相同的过滤逻辑
        // 1. 筛选合同结束时间在今年的数据
        List<CloudNetwork> filteredByTime = filterValidContractEndTime(allNetworks);

        // 2. 获取所有providerType='未招标'的数据
        List<CloudNetwork> weizhaobiaoNetworks = allNetworks.stream()
                .filter(network -> "未招标".equals(network.getProviderType()))
                .collect(Collectors.toList());

        // 3. 合并结果：合同结束时间在今年的数据 + 所有未招标的数据
        Set<CloudNetwork> mergedSet = new LinkedHashSet<>(filteredByTime);
        mergedSet.addAll(weizhaobiaoNetworks);
        List<CloudNetwork> filteredNetworks = new ArrayList<>(mergedSet);

        // 按城市代码分组计数
        Map<String, Long> filteredCounts = filteredNetworks.stream()
                .collect(Collectors.groupingBy(CloudNetwork::getCityCode, Collectors.counting()));

        // 转换为与SQL查询相同的格式
        return allCounts.stream()
                .map(countMap -> {
                    String city = (String) countMap.get("cityCode");
                    Long count = filteredCounts.getOrDefault(city, 0L);

                    Map<String, Object> result = new HashMap<>();
                    result.put("cityCode", city);
                    result.put("totalCount", count);
                    return result;
                })
                .filter(map -> (Long) map.get("totalCount") > 0) // 只返回有数据的城市
                .collect(Collectors.toList());
    }
}
